/**
 * Copyright (c) 2017-2024 Nop Platform. All rights reserved.
 * Author: canonical_entropy@163.com
 * Blog:   https://www.zhihu.com/people/canonical-entropy
 * Gitee:  https://gitee.com/canonical-entropy/nop-entropy
 * Github: https://github.com/entropy-cloud/nop-entropy
 */
package com.gitee.wsl.struct.table.impl

import com.gitee.wsl.struct.table.ICell
import com.gitee.wsl.struct.table.IRow
import com.gitee.wsl.struct.table.ITableView


abstract class AbstractRow() : IRow {

    override var table: ITableView? = null

    override var isFrozen: Boolean = false

    override var id: String? = null
        set(id) {
            checkAllowChange()
            field = id
        }

    override val styleId: String?
        get() = null

    override val height: Double?
        get() = null

    override val isHidden: Boolean
        get() = false

    override fun freeze(cascade: Boolean) {
        //super.freeze(cascade)
        if (cascade) {
            for (cell in cells) {
                cell?.freeze(true)
            }
        }
    }

    /*
     * 因为行中需要记录proxy, 所以单行无法实现copy语义 protected void copyTo(BaseRow row) { row.rowId = rowId; row.customProps =
     * MapHelper.clone(customProps); row.model = model; }
     */
    override fun toString(): String {
        val sb = StringBuilder()
        sb.append("Row[")
        if (id != null) {
            sb.append("id=").append(id).append(',')
        }
        sb.append("colCount=").append(cells.size)
        appendInfo(sb)
        sb.append("]")
        return sb.toString()
    }

    protected fun appendInfo(sb: StringBuilder) {
    }

    override val isEmpty: Boolean
        get() = cells.isEmpty()


    override val colCount: Int
        get() = cells.size

    override fun getCell(i: Int): ICell? {
        if (i < 0 || i >= cells.size) return null
        return cells[i]
    }

    override fun internalSetCell(colIndex: Int, cell: ICell?) {
        checkAllowChange()
        if (cell != null) cell.row = this

        for (j in cells.size..colIndex) {
            cells.add(null)
        }
        cells[colIndex] = cell
    }

    override fun internalRemoveCell(colIndex: Int) {
        checkAllowChange()
        if (colIndex >= cells.size) return
        cells.removeAt(colIndex)
    }

    override fun internalInsertCell(colIndex: Int, cell: ICell?) {
        checkAllowChange()
        cell?.row = this
        if (cells.size < colIndex) {
            for (j in cells.size until colIndex) {
                cells.add(null)
            }
            cells.add(cell)
        } else {
            cells.add(colIndex, cell)
        }
    }

    override fun internalAddCells(cells: Collection<ICell>) {
        checkAllowChange()

            for (cell in cells) {
                internalAddCell(cell)
            }

    }

    override fun internalAddCell(cell: ICell) {
        checkAllowChange()
        cell.row = this
        cells.add(cell)
    }

}